#!/bin/bash

# 默认值（可通过环境变量覆盖）
NGINX_ROOT="${NGINX_ROOT:-/usr/share/nginx/html}"
CERT_DIR="/etc/nginx/ssl"
KEY_FILE="$CERT_DIR/bingbingyihao.cn.key"
PEM_FILE="$CERT_DIR/bingbingyihao.cn.pem"

# 证书源路径（相对于脚本所在目录的上级 ssl/ 目录）
SOURCE_CERT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/ssl"
SOURCE_KEY="$SOURCE_CERT_DIR/bingbingyihao.cn.key"
SOURCE_PEM="$SOURCE_CERT_DIR/bingbingyihao.cn.pem"

echo "⚙️ 正在配置 Nginx 支持 HTTPS..."

# 创建 Nginx 根目录
if [ -e "$NGINX_ROOT" ] && [ ! -d "$NGINX_ROOT" ]; then
    echo "❌ $NGINX_ROOT 存在但不是目录，正在删除..."
    sudo rm -f "$NGINX_ROOT"
fi

if [ ! -d "$NGINX_ROOT" ]; then
    echo "📁 创建 Nginx 静态目录: $NGINX_ROOT"
    sudo mkdir -p "$NGINX_ROOT"
    sudo chown -R $(whoami):$(whoami) "$NGINX_ROOT"
fi

# 检查并复制证书文件
echo "🔐 正在检查本地证书文件..."
if [ ! -f "$SOURCE_KEY" ]; then
    echo "❌ 私钥文件不存在: $SOURCE_KEY"
    echo "   请确认文件位于: ../ssl/bingbingyihao.cn.key"
    exit 1
fi

if [ ! -f "$SOURCE_PEM" ]; then
    echo "❌ 证书文件不存在: $SOURCE_PEM"
    echo "   请确认文件位于: ../ssl/bingbingyihao.cn.pem"
    exit 1
fi

# 创建目标证书目录并复制文件
sudo mkdir -p "$CERT_DIR"
echo "✅ 发现证书文件，正在安装到 $CERT_DIR..."
sudo cp "$SOURCE_KEY" "$KEY_FILE"
sudo cp "$SOURCE_PEM" "$PEM_FILE"
sudo chmod 600 "$KEY_FILE" "$PEM_FILE"
sudo chown root:root "$KEY_FILE" "$PEM_FILE"
echo "✅ 证书已成功部署到系统目录"

# 写入 Nginx 配置（HTTPS + HTTP 跳转）
sudo tee /etc/nginx/nginx.conf > /dev/null << EOF
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                      '\$status \$body_bytes_sent "\$http_referer" '
                      '"\$http_user_agent" "\$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    keepalive_timeout  65;

    # Gzip 压缩优化
    gzip  on;
    gzip_types text/plain application/json application/javascript text/css;

    # 请求频率限制
    limit_req_zone \$binary_remote_addr zone=frontend:10m rate=10r/s;

    # ========== HTTP Server (自动跳转到 HTTPS) ==========
    server {
        listen 80;
        server_name bingbingyihao.cn www.bingbingyihao.cn;

        # 强制跳转 HTTPS
        return 301 https://\$host\$request_uri;
    }

    # ========== HTTPS 用户端 Server ==========
    server {
        listen 443 ssl http2;
        server_name bingbingyihao.cn www.bingbingyihao.cn;

        root /usr/share/nginx/html/user;
        index index.html;

        client_max_body_size 5M;

        # SSL 证书配置
        ssl_certificate      $PEM_FILE;
        ssl_certificate_key  $KEY_FILE;

        # 安全设置
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384;
        ssl_prefer_server_ciphers off;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;

        # HSTS 安全头（建议开启）
        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;
        add_header X-XSS-Protection "1; mode=block";

        location / {
            try_files \$uri \$uri/ /index.html;
            limit_req zone=frontend burst=20 nodelay;
        }

        location /api/ {
            proxy_pass http://localhost:8080/api/;
            proxy_set_header Host \$host;
            proxy_set_header X-Real-IP \$remote_addr;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto \$scheme;
        }

        location ~* ^/(?!api/).+\\.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            limit_req zone=frontend burst=5 nodelay;
        }
    }

    # ========== 管理端 Server (HTTPS) ==========
    server {
        listen 10000 ssl;
        server_name localhost;

        root /usr/share/nginx/html/admin;
        index index.html;

        # 使用相同证书保护管理后台
        ssl_certificate      $PEM_FILE;
        ssl_certificate_key  $KEY_FILE;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;

        location / {
            try_files \$uri \$uri/ /index.html;
            limit_req zone=frontend burst=20 nodelay;
        }

        location /api/ {
            proxy_pass http://localhost:10010/api/;
            proxy_set_header Host \$host;
            proxy_set_header X-Real-IP \$remote_addr;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto \$scheme;
        }

        location ~* ^/(?!api/).+\\.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            limit_req zone=frontend burst=5 nodelay;
        }
    }
}
EOF

# 测试并重启 Nginx
echo "🔄 正在测试 Nginx 配置..."
sudo nginx -t
if [ $? -eq 0 ]; then
    echo "✅ 配置正确，正在重启 Nginx..."
    sudo systemctl restart nginx
    echo "✅ Nginx 已成功重启，HTTPS 服务启动！"
    echo "🌐 访问站点: https://bingbingyihao.cn"
    echo "🛡️  管理后台: https://bingbingyihao.cn:10000"
else
    echo "❌ Nginx 配置错误，请检查 /etc/nginx/nginx.conf"
    exit 1
fi
